﻿using UnityEngine;
using System.Collections;

/// <summary>
/// 메쉬 관련 클래스.
/// </summary>
public static class wsMesh
{
	/// <summary>
	/// 평면 메쉬 생성하기.
	/// </summary>
	/// <param name="name">메쉬 이름</param>
	/// <param name="widthSegments">가로 조각 수</param>
	/// <param name="heightSegments">세로 조각 수</param>
	/// <param name="width">가로 크기</param>
	/// <param name="height">세로 크기</param>
	/// <param name="vertical">수직으로 세우기</param>
	/// <returns>생성된 메쉬</returns>
	public static Mesh CreatePlaneMesh(string name, int widthSegments, int heightSegments, int width, int height, bool vertical)
	{
		int width_segments = Mathf.Clamp(widthSegments, 1, 254);
		int height_segments = Mathf.Clamp(heightSegments, 1, 254);

		Mesh m = new Mesh();
		m.name = name;

		int hCount2 = width_segments + 1;
		int vCount2 = height_segments + 1;
		int numTriangles = width_segments * height_segments * 6;
		int numVertices = hCount2 * vCount2;

		Vector3[] vertices = new Vector3[numVertices];
		Vector2[] uvs = new Vector2[numVertices];
		Color[] colors = new Color[numVertices];
		int[] triangles = new int[numTriangles];

		int index = 0;
		float uvFactorX = 1.0f / width_segments;
		float uvFactorY = 1.0f / height_segments;
		float scaleX = width / width_segments;
		float scaleY = height / height_segments;

		float halfWidth = width / 2.0f;
		float halfHeight = height / 2.0f;

		float realX = -halfWidth;
		float realY = -halfHeight;

		for (float y = 0.0f; y < vCount2; y++)
		{
			for (float x = 0.0f; x < hCount2; x++)
			{
				if (vertical)
				{
					vertices[index] = new Vector3(x * scaleX + realX, y * scaleY + realY, 0.0f);
				}
				else
				{
					vertices[index] = new Vector3(x * scaleX + realX, 0.0f, y * scaleY + realY);
				}

				uvs[index++] = new Vector2(x * uvFactorX, y * uvFactorY);
			}
		}

		index = 0;
		for (int y = 0; y < height_segments; y++)
		{
			for (int x = 0; x < width_segments; x++)
			{
				triangles[index] = (y * hCount2) + x;
				triangles[index + 1] = ((y + 1) * hCount2) + x;
				triangles[index + 2] = (y * hCount2) + x + 1;

				triangles[index + 3] = ((y + 1) * hCount2) + x;
				triangles[index + 4] = ((y + 1) * hCount2) + x + 1;
				triangles[index + 5] = (y * hCount2) + x + 1;
				index += 6;
			}
		}

		m.vertices = vertices;
		m.uv = uvs;
		m.colors = colors;
		m.triangles = triangles;
		m.RecalculateNormals();

		return m;
	}

}
